<template>
	<view class="content">
		<u-navbar :fixed="false" title="不合格评审" titleStyle="color:#fff;">
			<view class="u-nav-slot" slot="left">
				<view class="NavbarLeft">
					<!-- 回退按钮 -->
					<u-icon name="arrow-left" :duration="0" size="20" color="#fff" @click="GoBack"></u-icon>
				</view>
			</view>
		</u-navbar>

		<view class="MainBox">
			<u--form class="topForm" labelPosition="left" :model="formData" ref="uForm">

				<u-form-item labelWidth="100" label="单据日期" prop="BillDate" borderBottom>
					<u--input v-model="formData.BillDate" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="单据编号" prop="BillNO" borderBottom>
					<u--input v-model="formData.BillNO" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="来源信息" prop="InformationSource" borderBottom>
					<u--input v-model="formData.InformationSource" disabled disabledColor="#ffffff"
						border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="品号" prop="ProductCode" borderBottom>
					<u--input v-model="formData.ProductCode" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="品名" prop="ProductName" borderBottom>
					<u--input v-model="formData.ProductName" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="规格" prop="ProductSpec" borderBottom>
					<u--input v-model="formData.ProductSpec" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="送检数量" prop="Qty" borderBottom>
					<u--input v-model="formData.Qty" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="责任部门" prop="ClassName" borderBottom
					@click="openBaseScreen('责任部门','radio')" required>
					<u--input v-model="formData.ClassName" placeholder="请选择责任部门" disabled disabledColor="#ffffff"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right" color="#999"></u-icon>
				</u-form-item>
				<u-form-item labelWidth="100" label="申请人" prop="UserName" borderBottom>
					<u--input v-model="formData.UserName" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="备注" prop="FRemarks" borderBottom>
					<u--input v-model="formData.FRemarks" placeholder="请输入备注" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="异常描述" prop="Comment" borderBottom>
					<u--input v-model="formData.Comment" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="处置意见" prop="DisposalOpinion" borderBottom>
					<u--input v-model="formData.DisposalOpinion" disabled disabledColor="#ffffff"
						border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="最终结果" prop="EndResult" borderBottom>
					<u--input v-model="formData.EndResult" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>
				<u-form-item labelWidth="100" label="审批状态" prop="ReviewStatus">
					<u--input v-model="formData.ReviewStatus" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>

			</u--form>

			<view class="BottomCard" v-if="FormData_A.BHGPSID">
				<view class="Title">
					<text>流程</text>
				</view>

				<view class="CellBox x-f CardTop">
					<view class="leftBox">
						<text>{{SponsorData.UserName}}</text>

						<!-- 状态图标 -->
						<view class="statusType">
							<!-- <uni-icons class="Icon" color="#36c601" custom-prefix="iconfont" type="icon-success"
								size="18"></uni-icons> -->
							<uni-icons fontFamily="CustomFontPlatform" class="Icon" color="#36c601"
								:size="18">{{$utils.toUniCode('&#xe610;')}}</uni-icons>
						</view>

						<!-- 线 -->
						<view class="line"></view>
					</view>

					<view style="flex: 1;">
						<u-cell title="发起审批" :value="DateBack(SponsorData.CreateTime,'Y-MM-dd hh:mm:ss')"
							:label="SponsorData.UserName"></u-cell>
					</view>
				</view>


				<view v-for="(item,index) in approvalList" :key="index">
					<view v-for="(ReItem,ind) in item.approvalNodeList" :key="ind">

						<view class="CellBox x-f CardMainBox" v-for="(row,inds) in ReItem.node" :key="inds">
							<view class="leftBox">
								<uni-icons v-if="row.CurrentApprovalIDs.length > 1" type="staff" color="#fff"
									size="30"></uni-icons>

								<text v-else>{{row.CurrentApprovalIDs[0]}}</text>



								<!-- 状态图标 -->
								<view class="statusType" v-if="item.level >= ReItem.index - 1">
									<!-- <uni-icons v-if="row.Approve == 0" class="Icon" color="#ef8b38"
										custom-prefix="iconfont" type="icon-wait" size="18"></uni-icons> -->

									<uni-icons v-if="row.Approve == 0" fontFamily="CustomFontPlatform" class="Icon"
										color="#ef8b38" :size="18">{{$utils.toUniCode('&#xe606;')}}</uni-icons>

									<!-- <uni-icons v-else-if="row.Approve == 1" class="Icon" color="#36c601"
										custom-prefix="iconfont" type="icon-success" size="18"></uni-icons> -->

									<uni-icons v-else-if="row.Approve == 1" fontFamily="CustomFontPlatform" class="Icon"
										color="#36c601" :size="18">{{$utils.toUniCode('&#xe610;')}}</uni-icons>

									<!-- <uni-icons v-else-if="row.Approve == 2" class="Icon" color="#d81e06"
										custom-prefix="iconfont" type="icon-dengdaidaishen" size="18"></uni-icons> -->
									<uni-icons v-else-if="row.Approve == 2" fontFamily="CustomFontPlatform" class="Icon"
										color="#d81e06" :size="18">{{$utils.toUniCode('&#xe605;')}}</uni-icons>
								</view>
							</view>

							<view style="flex: 1;">
								<u-cell>
									<template #title>
										<view v-if="row.ApprovalContent" class="ApproveClass"
											:class="{'successApprove':(row.Approve == 1)}">
											<text>{{row.Approver}}："</text>
											<text>{{row.ApprovalContent}}</text>"
										</view>
									</template>
								</u-cell>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 审批弹层 -->
			<u-modal :show="approveShow" :showCancelButton="true" @confirm="confirmApprove" @cancel="cancelApprove">
				<view class="slot-content">
					<view class="x-f">
						<text style="color: #333;margin-right: 8px;">审批意见</text>
						<u--input placeholder="请输入审批意见" border="surround" v-model="SubValue"></u--input>
					</view>
				</view>
			</u-modal>

			<!-- 最终审批弹层 -->
			<u-modal :show="showFinal" :showCancelButton="true" @confirm="FinalConfirm" @cancel="FinalCancel">
				<view class="slot-content">

					<view class="x-f">
						<text style="color: #333;margin-right: 8px;">处置意见:</text>
						<view @click="openBaseScreen('处置意见','radio')">
							<u--input placeholder="请选择处置意见" border="bottom" readonly
								v-model="DisposalOpinionName"></u--input>
						</view>
						<u-icon name="arrow-right" color="#999" size="20"></u-icon>

					</view>

					<view class="x-f" style="margin-top: 10px;">
						<text style="color: #333;margin-right: 8px;">最终结果:</text>
						<u--input placeholder="请输入最终结果" border="bottom" v-model="SubValue"></u--input>
					</view>
				</view>
			</u-modal>
		</view>


		<view class="BottomBox">
			<view class="SubBtn" v-if="!FormData_A.BHGPSID" @click="handlerApprove">发起审批</view>

			<view class="SubBtn" v-if="approveFalg" @click="submit(0)">重新发起审批</view>

			<view class="SubBtn" v-if="btnShow" @click="submit(1)">输入审核意见/确认同意</view>
			<view class="SubBtn" v-if="btnShow" @click="submit(2)">拒绝</view>

			<view class="SubBtn" v-if="finalBtn  && formData.Status != 2" @click="showFinal = true">最终评审</view>
		</view>


	</view>
</template>

<script>
	// 不合格评审
	export default {
		data() {
			return {
				BadReviewID: null, // 不合格评审主键id
				formData: {
					APFlowID: '',
					BadReviewID: '',
					FType: '',
					BillDate: '',
					BillNO: '',
					InformationSource: '',
					ProductCode: '',
					ProductName: '',
					ProductSpec: '',
					ClassID: '',
					ClassName: '',
					Qty: '',
					FRemarks: '',
					Comment: '',
					InspectionSheetID: '',
					FirstInspectionID: '',
					TourInspectionID: '',
					FinalInspectionID: '',
					FinishedInspectionID: '',
					ReviewStatusID: '',
					ReviewStatus: '',
					FRemarks1: '',
					Status: '',
					FQR: '',
					UserName: '',
					Rank: '',
				},
				FormData_A: {
					BHGPSID: null,
					Ck_BHGPSReviewID: null,
				},
				UserInfo: {},
				SponsorData: {}, // 发起人数据
				approvalList: [], // 流程数据
				btnShow: false, // 是否可以审批 （ 同意 - 拒绝 ）
				approveFalg: false, // 是否展示重新发起审批
				approveShow: false, // 按钮组弹层
				SubValue: '', // 输入框
				finalResult: false,
				finalBtn: false, // 是否显示 最终评审按钮
				DisposalOpinion: '', // 处置意见
				DisposalOpinionName: '',
				showFinal: false, // 最终评审弹层
			};
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			var that = this;
			this.BadReviewID = option.id;

			that.UserInfo = JSON.parse(that.Request.UserInfo());

			setTimeout(() => {
				that.GetPageAllow();
				// that.getPageInfo();
			}, 300)
		},
		mounted() {
			var that = this;
			uni.$on('ReviewInfo_Choice', function(ret) {
				if (ret.type == '责任部门') {
					that.formData.ClassName = ret.data.ClassName;
					that.formData.ClassID = ret.data.ClassID;
				} else if (ret.type == '处置意见') {
					that.DisposalOpinionName = ret.data.name;
					that.DisposalOpinion = ret.data.DisposalOpinion;
				}
			});
		},
		onUnload() { // 监听页面卸载,
			// 关闭监听器
			uni.$off('ReviewInfo_Choice');
		},
		methods: {
			DateBack(date, Type) {
				var that = this;
				return that.Request.dateFormat(date, Type);
			},
			GetPageAllow() {
				var that = this;

				that.Request.request('selectBHGPSIDByDGID', {
					BadReviewID: that.BadReviewID,
					ReviewType: 1,
				}, function(ret) {
					if (ret.status == 200) {
						if (ret.data.ds.length) { // 获取评审流程
							that.FormData_A = Object.assign(that.FormData_A, ret.data.ds[0]);
							that.FormData_A.BHGPSID = ret.data.ds[0]['BHGPSID'];


						}
						that.getPageInfo();

						that.checkIsShowButton();

					}
				});

			},
			checkIsShowButton: function() { // 是否可以审批
				var that = this;
				var obj = {
					P_TableName: 'QC_BadReview',
					P_PKValue: that.BadReviewID,
					UserID: that.UserInfo.UserID,
				}
				that.Request.request('WhetherItCanBeApproved', obj, function(res) {
					if (res.status == 200) {
						that.btnShow = res.data.ds[0].ISSP == 1 ? true : false;
						that.ApprovalSort = res.data.ds[0].ApprovalSort;
					}
				})
			},
			getPageInfo() {
				var that = this;

				that.Request.request('APP_BHGPSMX', {
					BadReviewID: that.BadReviewID
				}, function(ret) {
					if (ret.status == 200) {

						that.formData = Object.assign(that.formData, ret.data.ds[0]);

						that.getHistoryData();
					}
				});
			},
			handlerApprove() { // 发起审批
				var that = this;

				if (!that.formData.ClassID) {
					return uni.showToast({
						title: '请选择责任部门',
						icon: 'none'
					})
				}
				let obj1 = {
					Comment: that.formData.Comment,
					ClassID: that.formData.ClassID,
					FRemarks: that.formData.FRemarks,
					BadReviewID: that.BadReviewID,
				};

				that.Request.request('APP_BHGPS_UPDATE', obj1, function(reSt) {
					if (reSt.data.ds[0].status == 200) {


						let obj2 = {
							UserID: that.UserInfo.UserID,
							ReviewType: 1,
							IsReworkDepart: -1,
							BadReviewID: that.BadReviewID,
						};

						/* APP不合格评审单修改接口 */
						that.Request.request('addBHGPSReviewApprove', obj2, function(ret) {
							if (ret.status == 200) {
								if (ret.data.ds.length) {
									that.FormData_A.BHGPSID = ret.data.ds[0]['Ck_ReviewID'];

									let obj3 = {
										approveType: 0,
										APFlowID: 1,
										BadReviewID: that.BadReviewID,
										ReviewType: 1,
										UserID: that.UserInfo.UserID,
									};

									/* 开始审批审批流 */
									that.Request.request('BhgpsbgApprove', obj3, function(RES) {
										if (RES.status == 200) {

											if (RES.data.ds[0].status == 500) {
												uni.showToast({
													title: RES.data.ds[0].msg,
													icon: 'none'
												})
											} else {
												that.GetPageAllow();
												that.getPageInfo();
												uni.showToast({
													title: '发起成功'
												})
											}

										}
									});
								}

							}
						});
					}
				});
			},
			getHistoryData() {
				let that = this;
				// 获取发起人数据
				that.Request.request('getBHGPSCkReviewByID', {
					Ck_ReviewID: that.FormData_A.BHGPSID,
					ReviewType: 1,
				}, function(ret) {
					if (ret.status == 200 && ret.data.ds.length) {
						that.SponsorData = ret.data.ds[0];

						that.Request.request('Select_FlowLog1', {
							BadReviewID: that.BadReviewID,
							P_TableName: 'QC_BadReview',
						}, function(res) {
							if (res.status == 200 && res.data.ds.length) {
								if (that.UserInfo.UserName == res.data.ds[0].Creater) {
									res.data.ds.map((item) => {
										if (item.Approve == 2) {
											that.approveFalg = true;
										} else {
											that.approveFalg = false;

										}
									})
								}


								var data = [];
								var allCurrentApprovalIDs = [];
								var allCurrentApprovalIDs2 = [];

								for (let [index, item] of res.data.ds.entries()) {
									item.CurrentApprovalIDs = item.CurrentApprovalIDs ?
										item.CurrentApprovalIDs.replace(/^,+/, "").replace(/,+$/, "")
										.split(',') : '';

									allCurrentApprovalIDs = allCurrentApprovalIDs.concat(item
										.CurrentApprovalIDs);

									if (item.FlowType != 1) {
										allCurrentApprovalIDs2 = allCurrentApprovalIDs2.concat(item
											.CurrentApprovalIDs);
									}

									if (data.indexOf(item.AuditID) == -1) {
										data.push(item.AuditID);
									}
								}

								var approvalList = [];

								for (let [index, item] of data.entries()) {
									var approvalNodeList = [];
									var level = 0;
									var finLevel = 0;

									for (let [ind, ReItem] of res.data.ds.entries()) {
										if (data[index] == ReItem.AuditID) {
											if (ReItem.Approve == 0 && !level) {
												level = ReItem.ApprovalSort;
											}

											if (ReItem.Approve == 1 && ind == res.data.ds.length -
												1) {
												level = ReItem.ApprovalSort;
											}

											if (ReItem.Approve == 2 && !finLevel) {
												finLevel = ReItem.ApprovalSort;
											}

											if (ReItem.Approve == 2 && index == data.length - 1) {
												that.finalResult = true;
											}

											var x = 0;
											for (let [inds, Row] of approvalNodeList.entries()) {
												if (Row.index == ReItem.ApprovalSort) {
													x = 1;
													Row.node.push(ReItem);
												}
											}
											if (!x) {
												approvalNodeList.push({
													index: ReItem.ApprovalSort,
													type: ReItem.FlowType,
													department: ReItem.ApprovalName,
													node: [ReItem]
												})
											}
										}

									}

									// 限制了这个人才能看见最终审批
									if (res.data.ds[res.data.ds.length - 1].Approve == 1 && that.UserInfo
										.UserID == '1589') {
										that.finalBtn = true;
									}
									approvalList.push({
										level: finLevel ? (finLevel - 1) : (level - 1),
										approvalNodeList: approvalNodeList
									})
								};
								that.approvalList = approvalList;


							}
						})
					}
				})

			},
			submit(flag) { // 底部按钮组
				var that = this
				that.approveFlag = flag;
				if (flag) { //同意/拒绝
					that.approveShow = true;
				} else { //重新发起审批
					let obj = {
						Ck_BHGPSReviewID: that.FormData_A.Ck_BHGPSReviewID,
						NgCause: '',
						BadReviewID: that.formData.BadReviewID,
						UserID: that.UserInfo.UserID,
						ClassID: that.formData.ClassID,
						IsReworkDepart: 1,
						ReviewType: 1,
						P_Timeout: 0,
					}
					that.Request.request('updateBHGPSApproveReview', obj, function(res) {
						if (res.ds && res.ds[0].status == 500) {
							// vm.$toast(res.ds[0].msg)
						} else {
							that.handlerApprove()
							// vm.$toast('重新发起审批成功！')
						}
					})
				}
			},
			confirmApprove() { // 弹层确认按钮
				var that = this;
				/**
				 * 1、判断责任部门
				 */
				if (!this.formData.ClassName) {
					return uni.showToast({
						title: '请选择责任部门',
						icon: 'none'
					})
				}

				var obj = {
					ApprovalSort: this.ApprovalSort,
					BadReviewID: this.formData.BadReviewID,
					ApprovalContent: this.SubValue,
					APFlowID: 1,
					Approve: that.approveFlag == 1 ? 1 : 2,
					TableName: 'QC_BadReview',
					UserID: that.UserInfo.UserID,
				}
				that.Request.request('Ck_ApprovalForm', obj, function(res) {
					if (res.status == 200) {


						/* 更改审批状态 */
						that.Request.request('selectBHGPSSPZTByUserID', {
							BadReviewID: that.formData.BadReviewID,
							UserID: that.UserInfo.UserID,
							ReviewType: 1,
							status: that.approveFlag == 1 ? 1 : 2,
						}, function(ret) {
							that.GetPageAllow();

							that.cancelApprove()
						})


						uni.showToast({
							title: res.data.ds[0].msg
						})
					} else {
						uni.showToast({
							title: res.data.ds[0].msg,
							icon: 'none'
						})
					}
				})

				that.approveShow = false;

			},
			cancelApprove() { // 弹层取消按钮
				this.approveShow = false;
				this.SubValue = '';
			},
			FinalConfirm() { // 确认最终评审
				var that = this;
				if (!this.DisposalOpinion) {
					return uni.showToast({
						title: '请选择处置意见',
						icon: 'none'
					})
				}
				let obj = {
					JYLX: this.formData.InformationSourceID,
					DisposalOpinion: this.DisposalOpinion,
					BadReviewID: this.formData.BadReviewID,
					EndResult: this.SubValue,
				}

				that.Request.request('UpdateJYDZZJG', obj, function(ret) {
					if (ret.data.ds[0].status == 200) {
						uni.showToast({
							title: '提交成功',
						})
						that.FinalCancel();
						that.GetPageAllow();
					} else {
						uni.showToast({
							title: ret.data.ds[0].msg,
							icon: 'none'
						})
					}

				})
			},
			FinalCancel() { // 取消最终评审
				this.showFinal = false;
				this.SubValue = '';
			},
			openBaseScreen(str, type) { // 前往筛选页
				let that = this;

				if (type == 'radio') {
					let obj = null;
					if (str == '责任部门') {

						obj = {
							allowClear: false,
							cmd: 'APP_BMXL',
							type: str,
							ListeningName: 'ReviewInfo_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: false, //是否分页
								// searchKey: '', //搜索关键词，应包含在param中
								showText: 'ClassName', //查询结果显示的字段
								// pageIndexStr: 'Pageindex', //分页页码字段，应包含在param中	
								// subText: [{
								// 	label: '描述',
								// 	labelKey: 'desc'
								// }],
								ChoiceDataKey: 'ClassID',
								ChoiceDataData: this.formData.ClassID,
							},
							param: {},

						}
					} else if (str == '处置意见') {

						obj = {
							allowClear: false,
							cmd: 'APP_CZYJXL',
							type: str,
							// ListeningName: 'Result_Choice', // 监听器
							ListeningName: 'ReviewInfo_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: false, //是否分页
								// searchKey: '', //搜索关键词，应包含在param中
								showText: 'name', //查询结果显示的字段
								// pageIndexStr: 'Pageindex', //分页页码字段，应包含在param中	
								// subText: [{
								// 	label: '描述',
								// 	labelKey: 'desc'
								// }],
								ChoiceDataKey: 'DisposalOpinion',
								ChoiceDataData: this.DisposalOpinionName,
							},
							param: {},

						}

					};

					that.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					});

					uni.navigateTo({
						url: '/commonPage/Tool/baseScreen'
					})
				} else if (type == 'other') {}
			},
			GoBack() {
				uni.navigateBack()
			},
		},
	}
</script>

<style lang="scss">
	.content {
		/* 给顶部盒子安全高度 */
		// padding-top: var(--status-bar-height);
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #fff;

		.MainBox {
			padding: 0 15px;
			flex: 1;
			overflow: auto;

			.topForm {
				background-color: #fff;

				.u-form-item__body {
					padding: 4px 0 !important;

					.u-form-item__body__left__content__label {
						font-size: 12px !important;
					}

					.u-input__content__field-wrapper__field {
						font-size: 12px !important;
					}
				}
			}

			.BottomCard {
				margin-top: 20px;
				min-height: 200px;
				box-shadow: 1px 1px 13px -9px #333;
				background-color: #fff;
				border-radius: 8px;
				padding: 10px 15px;

				.CellBox {
					.leftBox {
						position: relative;
						width: 44px;
						height: 44px;
						background-color: #0788ea;
						border-radius: 8px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 12px;
						color: #fff;
						text-align: center;
					}

					.statusType {
						position: absolute;
						right: -4px;
						bottom: -4px;
						width: 20px;
						height: 20px;
						border-radius: 999999px;
						background-color: #fff;
						padding: 2px;
					}

					.line {
						display: inline-block;
						background: #d6d6d6;
						position: absolute;
						top: 52px;
						left: 50%;
						transform: translateX(-50%);
						width: 3px;
						height: 24px;
						z-index: 2;
					}
				}

				.CardTop {
					margin-bottom: 26px;
				}

				.CardMainBox {
					margin-bottom: 10px;
				}

				.ApproveClass {
					color: #999;
				}

				.successApprove {
					color: #36c601 !important;
				}
			}
		}

		.BottomBox {
			padding: 10px 15px;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			width: 100%;

			.SubBtn {
				// width: 40%;
				min-width: 140px;
				width: fit-content;
				padding: 10px 15px;
				background-color: #51d0d0;
				color: #fff;
				border-radius: 12px;
				text-align: center;
				margin-left: 4px;
			}
		}
	}
</style>